﻿using ConsoleApplication.WebAPI;
using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HM
{
    [HotUpdate]
    [Description("聚合账核销结果，从销售合同下推销售退货")]
    public class HTPushRETURNSTOCK : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            try
            {
                var result = InvokeHelper.Login();
                var iResult = JObject.Parse(result)["LoginResultType"].Value<int>();
                if (iResult == 1)
                {
                    string FBILLNO = "", FEntryId = "", htFENTRYID = "";
                    string SQL = "/*dialect*/" + string.Format(@"
 SELECT (F_RXWU_Text6+T2.FNUMBER)F_RXWU_Text6 INTO #A1 from RXWU_t_Cust100002 t
					left join
					RXWU_t_Cust_Entry100013 t1 on  t.fid=t1.fid
					right JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID=T2.FMATERIALID
					WHERE T1.F_RXWU_Text2='销售出仓'

SELECT F_RXWU_Text6 into #F FROM RXWU_t_Cust_Entry100013 

                    select (T.F_RXWU_TEXT+t3.FNUMBER) AS PTDH, T.F_RXWU_TEXT,t3.FNUMBER,T1.FENTRYID,T.FBILLNO,T.FDATE into #C from T_CRM_CONTRACT t
					left join T_CRM_CONTRACTENTRY t1 on t.FID=t1.FID
					left join T_CRM_CONTRACTENTRY_R t2 on t1.FENTRYID=t2.FENTRYID
					LEFT join T_BD_MATERIAL t3 on t1.FMATERIALID=t3.FMATERIALID
					where t1.F_RXWU_QTY=0 and t2.FSALEQTY=0
					and t.fdate>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)

					SELECT row_number() over(partition by t3.FENTRYID order by t3.FENTRYID  ) as FSEQ, t3.FENTRYID htFENTRYID,T1.FEntryID,t3.FBILLNO into #D from RXWU_t_Cust100002 t
					left join
					RXWU_t_Cust_Entry100013 t1 on  t.fid=t1.fid
					LEFT JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID=T2.FMATERIALID
					right JOIN #C T3 ON T1.F_RXWU_Text6=T3.F_RXWU_TEXT AND T2.FNUMBER=T3.FNUMBER
					WHERE (T1.F_RXWU_Text2='销售出仓'
					and (T1.F_RXWU_TEXT15='AutoCheck'OR T1.F_RXWU_TEXT15='UserCheck')
                    AND  t3.FDATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
                    and (T1.F_RXWU_DATE2<=t3.FDATE) AND  t1.F_RXWU_Text16<>'补发订单' AND  t1.F_RXWU_Text16<>'换货订单')
					--or (T1.F_RXWU_DATE2 is null and T1.F_RXWU_Text2='销售出仓')

					SELECT row_number() over(partition by t3.FENTRYID order by t3.FENTRYID  ) as FSEQ, t3.FENTRYID htFENTRYID,T1.FEntryID,t3.FBILLNO into #E from RXWU_t_Cust100002 t
					left join
					RXWU_t_Cust_Entry100013 t1 on  t.fid=t1.fid
					LEFT JOIN T_BD_MATERIAL T2 ON T1.FMATERIALID=T2.FMATERIALID
					right JOIN #C T3 ON T1.F_RXWU_Text6=T3.F_RXWU_TEXT AND T2.FNUMBER=T3.FNUMBER
					where (t1.F_RXWU_Text16='补发订单' or  t1.F_RXWU_Text16='换货订单')
                    AND  t3.FDATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)

					select  * into #G FROM (
					SELECT * from #D where FSEQ=1
					UNION ALL
					SELECT * from #E where FSEQ=1
                    union all
					select row_number() over(partition by t1.FENTRYID order by t1.FENTRYID  ) as FSEQ,T1.FENTRYID htFENTRYID,0 FEntryID,T.fbillno from T_CRM_CONTRACT t
					left join T_CRM_CONTRACTENTRY t1 on t.FID=t1.FID
					left join T_CRM_CONTRACTENTRY_R t2 on t1.FENTRYID=t2.FENTRYID
					LEFT join T_BD_MATERIAL t3 on t1.FMATERIALID=t3.FMATERIALID
					where t1.F_RXWU_QTY=0 and t2.FSALEQTY=0 
					AND T.FDATE>(select max(fclosedate)fclosedate from t_stk_closeprofile where fcategory = 'STK' and FORGID=100071 group by forgid)
					AND T.F_RXWU_TEXT NOT IN (SELECT F_RXWU_Text6 FROM #F)
                    UNION ALL
                   
					select  row_number() over(partition by A.FENTRYID order by A.FENTRYID  ) as FSEQ,A.FENTRYID htFENTRYID,0 FEntryID,A.fbillno+A.FNUMBER from #C A
					WHERE A.PTDH NOT IN ( SELECT F_RXWU_Text6 FROM #A1) 
					)t 
                    SELECT DISTINCT * FROM #G   ");
                    DynamicObjectCollection DynamData = DBUtils.ExecuteDynamicObject(ctx, SQL);
                    if (DynamData.Count > 0)
                    {
                        for (int i = 0; i < DynamData.Count; i++)
                        {
                            FEntryId = Convert.ToString(DynamData[i]["FEntryId"]);
                            htFENTRYID = Convert.ToString(DynamData[i]["htFENTRYID"]);
                            FBILLNO = Convert.ToString(DynamData[i]["FBILLNO"]);
                            string json = "{\"Ids\":\"\",\"Numbers\":[],\"EntryIds\":\""+ htFENTRYID + "\",\"RuleId\":\"d06343e5-d56b-4b34-a70e-b3802ef6ff8c\",\"TargetBillTypeId\":\"\",\"TargetOrgId\":0,\"TargetFormId\":\"SAL_RETURNSTOCK\",\"IsEnableDefaultRule\":\"false\",\"IsDraftWhenSaveFail\":\"false\",\"CustomParams\":{}}";
                            result = InvokeHelper.Push("CRM_Contract", json.ToString());
                            JObject jobject = JObject.Parse(result);
                            string a = Convert.ToString(jobject["Result"]["ResponseStatus"]["IsSuccess"]);
                            bool IsSuccess = a == "True";
                            if (IsSuccess)
                            {
                                string SQL10 = "/*dialect*/" + string.Format(@"update T_CRM_CONTRACT set F_RXWU_Remarks='{1}',F_RXWU_CheckBox='1' where FBILLNO='{0}'", FBILLNO, result.ToString());
                                DBUtils.Execute(ctx, SQL10);
                            /* Log.WriteLog("从销售合同下推销售退货成功", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString()+ "平*/
                           // 台单号:"+ FBILLNO);
                                //string SQL1 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='1' where FEntryId='{0}'", FEntryId);
                                //DBUtils.Execute(ctx, SQL1);
                                var SuccessEntitysId = jobject["Result"]["ResponseStatus"]["SuccessEntitys"][0]["Id"];
                                string SQL2 = "/*dialect*/" + string.Format(@"update T_CRM_CONTRACT set FXYDJID='{1}' where FBILLNO='{0}'", FBILLNO, SuccessEntitysId);
                                DBUtils.Execute(ctx, SQL2);
                                string Submit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"SelectedPostId\":0,\"NetworkCtrl\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                result = InvokeHelper.Submit("SAL_RETURNSTOCK", Submit);
                                string Audit = "{\"CreateOrgId\":0,\"Numbers\":[],\"Ids\":\"" + SuccessEntitysId + "\",\"InterationFlags\":\"\",\"NetworkCtrl\":\"\",\"IsVerifyProcInst\":\"\",\"IgnoreInterationFlag\":\"\"}";
                                result = InvokeHelper.Audit("SAL_RETURNSTOCK", Audit);
                            }
                            else
                            {
                                string SQL10 = "/*dialect*/" + string.Format(@"update T_CRM_CONTRACT set F_RXWU_Remarks='{1}',F_RXWU_CheckBox='0' where FBILLNO='{0}'", FBILLNO, result.ToString());
                                DBUtils.Execute(ctx, SQL10);
                                //Log.WriteLog("从销售合同下推销售退货失败", "报文:" + json.ToString() + "/r/n" + "返回结果:" + result.ToString() + "平台单号:" + FBILLNO);
                                //string SQL1 = "/*dialect*/" + string.Format(@"update RXWU_t_Cust_Entry100013 set F_RXWU_COMBO='0' where FEntryId='{0}'", FEntryId);
                                //DBUtils.Execute(ctx, SQL1);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteLog("从销售合同下推销售退货程序报错", "原因:" + ex.ToString()+"CTX:"+ ctx.DBId);
            }
        }
    }
}
